package com.hopu.springbootdemo2.service.impl;



import com.hopu.springbootdemo2.entity.*;
import com.hopu.springbootdemo2.mapper.UserMapper;
import com.hopu.springbootdemo2.service.UserService;
import com.hopu.springbootdemo2.util.JwtUtils;
import com.hopu.springbootdemo2.util.MD5Utils;
import com.hopu.springbootdemo2.util.RsaUtils;
import org.springframework.cache.annotation.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * 业务逻辑实现类
 */
@CacheConfig(cacheNames = "user")
@Service
public class UserServiceImpl implements UserService {

//    public static final String KEY = "user:";

    //调用dao层对象
    @Resource
    private UserMapper userMapper;

//    @Resource
//    private RedisTemplate<String,Object> redisTemplate;

    @Cacheable(key = "T(String).valueOf(#userId)")
    @Override
    public User findById(String userId) {
//        //获得string类型的redis操作对象
//        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
//        //判断该id的用户在redis中是否存在
//        User user = (User) ops.get(KEY + userId);
//        //缓存存在，就直接返回
//        if(user != null){
//            return user;
//        }
//        //缓存不存在，再查询数据库
//        user = userMapper.selectById(userId);
//        //数据库中存在，保存到缓存中，返回数据
//        if(user != null){
//            ops.set(KEY + userId,user);
//        }
//        return user;
        return userMapper.selectById(userId);
    }

    @Override
    public PageEntity<User> findUserPage(Integer current, Integer pageSize) {
        //查询用户总数 count(*)
        int total = userMapper.selectUserCount();
        //分页查询用户数据 limit
        List<User> users = userMapper.selectUserLimit((current - 1) * pageSize, pageSize);
        //包装数据发送给前端
        PageEntity<User> pageEntity = new PageEntity<>();
        pageEntity.setCurrent(current);
        pageEntity.setPageSize(pageSize);
        pageEntity.setTotal(total);
        pageEntity.setRecords(users);
        return pageEntity;
    }

    /**
     * 登录业务逻辑
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserVO login(String username, String password) {
        //按用户名查询用户
        User user = userMapper.selectByUsername(username);
        if(user == null){
            return null;
        }
        //用户存在再判断密码，将用户填写的密码加密后，和数据库密码比较
        String pass = MD5Utils.md5(password);
        //相同就返回用户
        if(pass.equals(user.getUserPwd())){
            UserVO userVO = new UserVO();
            userVO.setUserId(user.getUserId());
            //生成Jwt字符串
            userVO.setToken(JwtUtils.generateToken(user.getUserName(), RsaUtils.privateKey,JwtUtils.EXPIRE_MINUTES));
            return userVO;
        }
        return null;
    }

    @Cacheable
    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    @CachePut(key = "T(String).valueOf(#user.userId)")
    @Override
    public User save(User user) {
        user.setUserPwd(MD5Utils.md5(user.getUserPwd()));
        userMapper.insert(user);
        return user;
    }

    @Caching(evict = {
            @CacheEvict(cacheNames = "user",key = "T(String).valueOf(#userId)"),
            @CacheEvict(cacheNames = "user",allEntries = true)})
//    @CacheEvict(key = "T(String).valueOf(#userId)")
    @Override
    public boolean remove(String userId) {
        return userMapper.delete(userId);
    }

//    @CachePut(key = "T(String).valueOf(#user.userId)")
    @Caching(put = @CachePut(cacheNames = "user",key = "T(String).valueOf(#user.userId)"),
    evict = @CacheEvict(cacheNames = "user",allEntries = true))
    @Override
    public User update(User user) {
        user.setUserPwd(MD5Utils.md5(user.getUserPwd()));
        userMapper.update(user);
        return user;
    }

    @Override
    public List<GrantedAuthority> findAuthoritiesByUsername(String username) {
        //查询所有权限
        List<Permission> permissions = userMapper.selectPermissionsByUsername(username);
        //查询所有角色
        List<Role> roles = userMapper.selectRolesByUsername(username);
        //拼接权限名到字符串中
        StringBuilder stringBuilder = new StringBuilder();
        for(Permission permission : permissions){
            stringBuilder.append(permission.getName() + ",");
        }
        for(Role role : roles){
            stringBuilder.append("ROLE_" + role.getName() + ",");
        }
        //删除末尾的逗号
        if(stringBuilder.toString().endsWith(",")){
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        //将字符串转为权限集合
        List<GrantedAuthority> authorities =
                AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuilder.toString());
        return authorities;
    }
}
